<template>
	<uni-popup ref="popup" type="bottom" :is-mask-click="false" background-color="#fff">
		<view class="header">
			<view class="header-title">兑换</view>
			<uni-icons type="close" @click="close"></uni-icons>
		</view>
		<view class="body">
			<view class="body-item">
				<uni-forms ref="form" :modelValue="formData" label-width="150rpx">
					<uni-forms-item label="兑换金额" name="price">
						<uni-easyinput v-model.number="formData.price" placeholder="" @change="priceChange">
							<template v-slot:right>
								<view style="color: blue;">福币</view>
							</template>
						</uni-easyinput>
						<view>实际到账<text style="color: red;">￥{{con_price/100}} 元</text></view>
						<view style="font-size: 12px;">20元起，D+1到账（服务费0.6%+单笔3元提现费）</view>
					</uni-forms-item>
					<uni-forms-item label="提现方式" name="type">
						<uni-data-checkbox  v-model="formData.type" :localdata="localType" />
						<text v-if="formData.type===0">自动提现：D+1到账</text>
						<text v-if="formData.type===1">人工提现：每周二审核到账</text>
					</uni-forms-item>
					<uni-forms-item label="提现二维码" name="img" v-if="formData.type===1">
						<uni-file-picker v-model="formData.img" limit="1" return-type="object"
							:imageStyles="imageStyles"></uni-file-picker>
					</uni-forms-item>
				</uni-forms>
				<button type="primary" size="mini" @click="submit">兑换</button>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	/**
	 * 兑换现金组件
	 */
	import {
		mapState,
		mapActions
	} from 'pinia'
	import {
		useUserStore
	} from "@/pinia/user.js"
	const db = uniCloud.database();
	const uniPayCo = uniCloud.importObject("uni-pay-co");
	var myOpenid; // 将openid临时缓存，避免重复获取openid
	export default {
		name: "wolf-exchange",
		data() {
			return {
				imageStyles: {
					width: 100,
					height: 100,
				},
				formData: {
					img: {},
					price: 0,
					type:0
				},
				localType:[{
					value:0,
					text:"自动提现"
				},{
					value:1,
					text:"人工付款"
				}],//提现类型
			};
		},
		async mounted() {
			let code;
			let res;
			if (!myOpenid) {
				// #ifdef MP-WEIXIN
				code = await this.getCode();
				res = await this.getOpenid({
					provider: "wxpay",
					code
				});
				if (res) myOpenid = res.openid;
				// #endif
			}
			console.log("myOpenid",myOpenid);
		},
		computed: {
			...mapState(useUserStore, ['userInfo']),
			con_price() {
				let price = this.formData.price * 10 - this.formData.price * 0.06 - 300
				if (price <= 0) {
					price = 0
				}
				console.log("con_price===>",price);
				return Math.floor(price)
			}
		},
		methods: {
			...mapActions(useUserStore, ['updateUserInfo']),
			open() {
				this.$refs.popup.open()
			},
			close() {
				this.$refs.popup.close()
			},
			submit() {
				let price = this.formData.price * 10
				if (price === 0 || price === NaN || (price > this.userInfo.gift_money) || price < 2000) {
					uni.showToast({
						title: '兑换金额错误',
						icon: "none"
					})
					return
				}
				if (!this.formData.img.url && this.formData.type===1) {
					uni.showToast({
						title: '请上传提现二维码',
						icon: "none"
					})
					return
				}
				let arr = []
				if(this.formData.type===0 && this.con_price>=40000){//如果是自动提现，并且金额大于400 自动分订单
					let len = parseInt(this.con_price/40000) +1
					let yprice = this.con_price%40000
					console.log("yprice",yprice);
					if(yprice<=30){//剩余金额小0.3元,减少一次循环，将剩余的加到第一次提现订单上
						len = len-1
					}
					for(let i=0;i<len;i++){
						let conprice
						if(i!=len-1){//如果不是最后一次循环
							conprice = 40000
						}else{
							if(yprice<=30){
								conprice = this.con_price-40000*i-yprice
							}else{
								conprice = this.con_price-40000*i
							}
						}
						if(i===0 && yprice <= 30){
							arr.push(this.getOrderList(price,conprice+yprice))
						}else{
							arr.push(this.getOrderList(price,conprice))
						}
					}
				}else{
					arr.push(this.getOrderList(price,this.con_price))
				}
				let money = this.userInfo.money - price
				// return console.log("arr>>>>",arr);
				this.updateUserInfo({
					money
				})
				db.collection('wolf-tixian').add(arr).then(res => {
					uni.showToast({
						title: '已提交',
						icon: "none"
					})
					this.$refs.popup.close()
				})
				console.log("DATA", this.formData)
			},
			getOrderList(price,conprice){
				let now = new Date().getTime() //获取当前时间戳
				let code = '' + (parseInt(Math.random() * 1000000) + 1000000)
				code = code.substring(1, 7)
				let order_no = "DH" + code + now //业务订单号
				let out_batch_no = order_no + 'x1'
				let obj = {
					img: this.formData.img,
					price: price,
					con_price: conprice,
					status: 0,
					uid: this.userInfo._id,
					order_id: order_no,
					create_time: now,
					out_batch_no,
					type: this.formData.type,
					openid:myOpenid,
					name:this.formData.name
				}
				return obj
			},
			priceChange() {
				console.log("this.form========>", this.formData.price, this.userInfo.gift_money);
				if (!this.userInfo?.gift_money) {
					this.userInfo.gift_money = 0
				}
				if (this.formData.price * 10 > this.userInfo.gift_money) {
					this.formData.price = this.userInfo.gift_money / 10
				}
			},
			/**
			 * 获取code
			 */
			getWeixinCode() {
				return new Promise((resolve, reject) => {
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success(res) {
							resolve(res.code)
						},
						fail(err) {
							reject(new Error('获取微信code失败'))
						}
					})
					// #endif
				})
			},
			// 获取code
			async getCode() {
				// #ifdef MP-WEIXIN
				return this.getWeixinCode();
				// #endif
			},
			// 根据code获取openid
			async getOpenid(data = {}) {
				try {
					let res = await uniPayCo.getOpenid(data);
					if (typeof data.success === "function") data.success(res);
					return res;
				} catch (err) {
					if (typeof data.fail === "function") data.fail(err);
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.header {
		display: flex;
		padding: 10rpx 20rpx;

		&-title {
			margin: auto;
		}
	}

	.tabber {
		display: flex;
		justify-content: space-between;
		font-size: 12px;
		padding: 10rpx 20rpx;

		&-gift {
			color: #c33864;
		}

		&-rechange {
			color: #fff;
			background-color: #FF5722;
			padding: 10rpx 20rpx;
			border-radius: 40rpx;
		}
	}

	.body {
		padding: 20rpx;
		display: flex;
		justify-content: center;
		min-height: 200px;

		&-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			border: 1px solid #fff;
			background-color: #fff;
			border-radius: 10rpx;
			padding-top: 10rpx;
			// color: #fff;
			// width: 300rpx;
			font-size: 14px;
			// height: 100px;

			&-btn {
				background-color: #c33864;
				width: 100%;
				border-bottom-left-radius: 10rpx;
				border-bottom-right-radius: 10rpx;
				padding: 10rpx 20rpx;
				text-align: center;
				box-sizing: border-box;
				margin-top: 10rpx;
			}
		}
	}
</style>